<template>
  <div>
    <el-dialog :width="changeRem(width)" :title="title" :visible.sync="visible" append-to-body>
      <el-form v-if="searchLabel && searchLabel.length" ref="queryForm" :inline="true">
        <el-form-item v-for="(item,index) in searchLabel" :label="searchLabelName[index]" prop="roleKey">
          <el-input
            v-model="params[item]"
            :placeholder="'请输入 '+ searchLabelName[index]"
            clearable
            size="small"
            style="width: 160px"
          />
        </el-form-item>
        <slot name="appendSearch" :data="params">
        </slot>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="search()">查询</el-button>
        </el-form-item>
      </el-form>
     <div class="option-box" v-loading="loading">
       <el-scrollbar>
         <el-table highlight-current-row :data="dataList" ref="multipleTable" height="300px" @selection-change="handleSelectionChange" @row-click="handleSelectionChange2">
           <el-table-column type="selection" width="50" align="center" v-if="multiple" :selectable="selectEnable" />
           <template v-for="(item,index) in labelFields">
             <el-table-column :prop="item" align="center" :label="labelFieldsName[index]"/>
           </template>
         </el-table>
       </el-scrollbar>
     </div>
      <div slot="footer" class="dialog-footer clearfix" style="text-align: right">
          <span class="btn-box" style="text-align: right;display: flex" v-if="total">
           <el-pagination
             @size-change="handleSizeChange"
             @current-change="handleCurrentChange"
             :page-sizes="[10,20,500,100, 200, 300, 400]"
             layout="total, prev, pager, next, jumper"
             :current-page="params[paramsMap.pageNum]"
             :page-size="params[paramsMap.pageSize]"
             style="margin-right: 20px"
             :total="total">
            </el-pagination>
             <el-button @click="visible = false" size="small">取 消</el-button>
             <el-button type="primary" size="small" @click="confirm">确 定</el-button>
          </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import BaseRequestComponent from "../../BaseRequestComponent";
import arr from "../../../../../utils/function/arr";
import {deepClone} from "vant/lib/utils/deep-clone";

export default {
  name: 'searchDialogObjectType2',
  extends:BaseRequestComponent,
  props: {
    visibleValue: {
      required: true,
      type: Boolean
    },
    clickClose: {
      type: Boolean,
      default: () => true
    },
    width: {
      default: '750px'
    },
    url: {
      required: true,
      type: String
    },
    params: {
      type: Object,
      default: () => ({
        pageNum: 1,
        pageSize: 20,
      })
    },
    value: {
      type: [Object,Array,Number,String],
      default: () => []
    },
    paramsMap: {
      type: Object,
      default: () => ({
        pageNum: 'pageNum',
        pageSize: 'pageSize',
      })
    },
    title: {
      default: '搜索'
    },
    searchKey: { // 查询请求的key
      default: 'nameOrNumber'
    },
    props: {
      type: Object,
      default: () => ({
        label: 'label',
        value: 'value'
      })
    },
    multiple: {
      type: Boolean,
      default: () => false
    }, // 是否多选
    pathPage: Boolean, // 分页参数是否在url上 格式：url/pageSize/page,
    labelFields: Array, // 下拉选项显示字段
    labelFieldsName: Array, // 下拉选项显示字段 的对应中文
    searchLabel: Array, // 搜索的字段名字
    searchLabelName: Array, // 搜索的字段中文名字
  },
  data() {
    return {
      queryParams:{},
      visible: false,
      dataList: [],
      activeItem: {},
      // 当前页选中的
      checkedValues: [],
      // 所有的选中的
      checkedValuesAllObj: {},
      total: 0,
      loading: false,
      // 不能操作的行 disable掉
      disabledRow:[],
    }
  },
 /* created() {
    if (this.url) {
      this.search()
    }
  },*/
  created () {
    this.checkedValuesAllObj = {}
  },
  updated() {
    // 在这里调用toggleSelection选中方法
    this.toggleSelection(this.dataList)
  },
  methods: {
    async search (url = this.url) {
      const param = this.params
      this.loading = true
      await this.getDict(url,param,this.$attrs.method || 'get')
      .then(res => {
        let status = eval(`res.${this.getDictResultMap.status}`)
        let data = eval(`res.${this.getDictResultMap.data}`)
        let total = eval(`res.${this.getDictResultMap.total}`)
        let list = eval(`res.${this.getDictResultMap.list}`)
        if (status === this.getDictSuccessStatus){
          if (data && list && list instanceof Array) {
            this.dataList = list || []
            this.total = total || 0
          } else if (data instanceof Array && data.length) {
            this.dataList = data || []
          }
          this.getCheckedValuesAllArr()
        }
      }).finally(() => {
        this.loading = false
      })
    },
    // 升级成功，不能勾选
    selectEnable(row, rowIndex) {
      let t = this.value.filter(item=>item[this.props.value]===row[this.props.value])
      if (!t || (t && t.length)) return false;
      return true;
    },
    toggleSelection (rows) {
      if (this.multiple) {
        if (this.value instanceof Array) {
          rows.forEach(row => {
            let t = this.value.filter(item=>
              item[this.props.value]===row[this.props.value]
            )
            if (t && t.length) {
              // toggleRowSelection  这个方法是用来选中某一行（打勾）
              // row 是要选中的那一行
              // true 是为选中
              let a = this.disabledRow.filter(item=>item[this.props.value]===t[0])
              if(!a || (a && !a.length)) {
                this.disabledRow.push(row)
              }
              this.$refs.multipleTable.toggleRowSelection(row, true)
            }
          })
        }
      }
    },
    toggleMyRowSelection (rows) {
      if (this.multiple) {
        if (this.checkedValues instanceof Array) {
          rows.forEach(row => {
            let t = this.checkedValues.filter(item=>item[this.props.value]===row[this.props.value])
            if (t && t.length) {
              this.$refs.multipleTable.toggleRowSelection(row, true)
            }
          })
        }
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection,item) {
      if (this.multiple) {
        if (selection instanceof Array) {
          this.checkedValues = selection;
        }
      }
    },
    // 单选框选中数据
    handleSelectionChange2(selection,item) {
      if (!this.multiple) {
        this.activeItem = selection
        this.$emit('dialogDataChange',this.activeItem)
        // 点击关闭的话，就
        if (this.clickClose){
          this.visible = false
        }
      }
    },
    confirm() {
      if (!this.multiple) {
        this.$emit('dialogDataChange',this.activeItem)
      } else {
        this.disabledRow.push(...this.getCheckedValuesAllArr())
        this.disabledRow = arr(this.disabledRow).unique(this.props.value).all();
        this.$emit('dialogDataChange',this.disabledRow)
      }
      this.visible = false
    },
    // 显示的内容
    getName (item) {
      if (this.labelFields.length) {
        return this.labelFields.map(i => item[i]).join(" ")
      } else {
        return item[this.props.number]?item[this.props.label]+item[this.props.number]:item[this.props.label]
      }
    },
    setClass(item) {
      if (this.activeItem[this.props.value] === item[this.props.value]) {
        return 'active-item'
      }
      return ''
    },
    changeRem(number) {
      return (parseFloat(number) * Math.min(this.$scale, 1)) + 'px'
    },
    handleSizeChange(size){
      this.params[this.paramsMap.pageSize] = size
      this.search()
    },
    async handleCurrentChange(size) {
      // 记录缓存，每页选中的项
      this.checkedValuesAllObj[this.params[this.paramsMap.pageNum]] = deepClone(this.checkedValues)
      this.params[this.paramsMap.pageNum] = size
      await this.search()
      this.getCurrentPageCheckedValues(size)
    },
    // 获取所有选中的数组
    getCheckedValuesAllArr(){
      this.checkedValuesAllObj[this.params[this.paramsMap.pageNum]] = deepClone(this.checkedValues)
      let t = []
      let values = Object.values(this.checkedValuesAllObj);
      if (values && values.length){
        values.map(i=>t.push(...i))
      }
      return t
    },
    /**
     * 获取当前页的选中项
     * @param size
     */
    getCurrentPageCheckedValues(size){
      this.$nextTick(function () {
        this.checkedValues = deepClone(this.checkedValuesAllObj[size] ? this.checkedValuesAllObj[size]:[])
        this.toggleMyRowSelection(this.dataList)
        this.toggleSelection(this.dataList)
      })
    }
  },
  watch: {
    visibleValue: {
      handler (val) {
        if (val !== this.visible) this.visible = val
        if (val && this.url) {
          this.search()
        }
        if (!val && this.multiple) {
          this.checkedValues = []
        }
      },
      immediate: true
    },
    visible (val) {
      if (this.visibleValue !== val) this.$emit('update:visibleValue', val)
    },
    keyword() {
      this.search()
    },
  }
}
</script>

<style scoped lang="scss">
  .option-box {
    height: 300px;
  }
  .drawing-list-wrap{
    padding: 0px;
    height: 300px;
    .list-item{
      list-style: none;
      margin: 0;
      cursor: pointer;
      padding: 12px 0 12px 5px;
      transition: all .3s ease-in;
      &:hover{
        background-color: #F5F7FA;
      }
      &:active {
        background-color: #409EFF;
      }
      border-bottom: 1px solid #f4f5f6;
    }
    .active-item {
      color: #409EFF;
    }
    ::v-deep .el-checkbox {
      display: inherit;
      margin: 0;
      padding: 12px 0 12px 5px;
      transition: all .3s ease-in;
    }
  }
  ::v-deep.el-scrollbar__wrap{
    overflow-x: hidden;
  }
  ::v-deep .el-icon-circle-check {
    display: none;
  }
.cursor{
  cursor: pointer;
}
  .dialog-footer {
    width: 100%;
    .page-box {
      float: left;
    }
    .btn-box {
      float: right;
    }
  }
</style>
